/*
 * jxSwing Project (2012, 2013, 2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxSwing.component.text;

import java.awt.Dimension;
import java.util.regex.PatternSyntaxException;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;

import org.jxSwing.i18n.I18N;
import org.jxUtils.JXConstants;

/**
 * @author Denilson Edinaldo Pinto
 * @project jxSwing
 * @package org.jxSwing.component.text
 * @date 21/09/2012 - 21:18:07
 */
public final class EmailField extends TextField {
	
	private static final long serialVersionUID = -4847471780997039205L;
	
	/**
     * 
     */
	public EmailField() {
	
		super();
		
		initGUI();
	}
	
	/**
	 * @param required
	 */
	public EmailField(final boolean required) {
	
		super(required);
		
		initGUI();
	}
	
	/**
	 * 
	 */
	private void initGUI() {
	
		setName(I18N.component().email());
		setSize(new Dimension(250, 25));
		setPreferredSize(new Dimension(250, 25));
		
		//
		setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(final JComponent input) {
			
				//
				if(isEmpty()) {
					
					return true;
					
				}else {
					
					boolean result = true;
					
					try {
						//
						result = getText().matches(JXConstants.EMAIL);
						
					}catch(final PatternSyntaxException parseException) {
						
						result = false;
					}
					
					//
					if( !result) {
						
						JOptionPane.showMessageDialog(EmailField.this, I18N.component().invalidValueEmail(getText()));
						
						setText("");
						requestFocusInWindow();
					}
					
					return result;
				}
			}
		});
	}
	
	/**
	 * @return {@code getText().trim().isEmpty()}
	 */
	public boolean isEmpty() {
	
		return getText().trim().isEmpty();
	}
}
